package com.pingpang.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import com.pingpang.util.IPUtil;
 
public class LoginHandlerInterceptor implements HandlerInterceptor {
	Logger logger = LoggerFactory.getLogger(LoginHandlerInterceptor.class);
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String basePath = request.getContextPath();
		String path = request.getRequestURI();
		String ip=IPUtil.getIpAddr(request);
		
		logger.info("--------------");
		logger.info("IP:"+ip);
		logger.info("basePath:" + basePath);
		logger.info("path:" + path);
		
		Object user = request.getSession().getAttribute("user");
		
		//判断是否是管理员
		boolean isAdmin=false;
		if(null!=request.getSession().getAttribute("isAdmin")) {
			isAdmin=true;
		}
		
        // 如果获取的request的session中的loginUser参数为空（未登录），就返回登录页，否则放行访问
        if (user == null) {
        	logger.info("未登录获取数据连接...");
        	logger.info("--------------");
            // 获取request返回页面到登录页
        	response.sendRedirect(request.getContextPath()+"/");
            return false;
        } else {
            // 已登录，放行
        	logger.info("--------------");
        	path=path.replaceFirst("^[/|\\\\]*", ""); 
        	if(path.startsWith("userController") || path.startsWith("druid")) {
        		if(!isAdmin) {
        		   logger.info(user+":非法请求，移除用户！！！");
        		   response.sendRedirect(request.getContextPath()+"/user/logOut");
                   return false;
        		}
                return isAdmin;        		
        	}
            return true;
        }
	}
}
